const express = require('express')
const router = express.Router()
const pool = require('../utils/pool')

// 查询所有房屋分类
router.get('/house/decoration', async (req, res, next) => {
  pool.query('select decoration, count(*) count from zh_properties group by decoration', (err, result) => {
    if (err) {
      return next(err)
    }
    if (result.length === 0) {
      return res.send({
        code: 4001,
        msg: '暂无房屋信息'
      })
    }
    res.send({
      code: 2000,
      msg: 'success',
      data: result
    })
  })
})

// 查询所有房屋每个分类对应的类型总数
router.get('/house/type', async (req, res, next) => {
  pool.query('select house_type, decoration, count(*) count from zh_properties group by decoration, house_type', (err, result) => {
    if (err) {
      return next(err)
    }
    if (result.length === 0) {
      return res.send({
        code: 4001,
        msg: '暂无房屋信息'
      })
    }
    res.send({
      code: 2000,
      msg: 'success',
      data: formatResults(result)
    })
  })
})

function formatResults(results) {
  const data = {};

  results.forEach(result => {
    const { house_type, decoration, count } = result;

    if (!data[decoration]) {
      data[decoration] = {};
    }

    data[decoration][house_type] = (data[decoration][house_type] || 0) + count;
  });

  // 将数据转换为数组形式
  const formattedArray = Object.entries(data).map(([decoration, houseTypes]) => ({
    [decoration]: houseTypes
  }));

  return formattedArray;
}

module.exports = router